<?php
namespace plugins\SmsMsg\controller;
use app\common\controller\Common;
use think\Validate;
use think\helper\Time;
use plugins\Alidayu\model\AlidayuSms;
require_once(dirname(dirname(__FILE__))."/sdk/TopClient.php");
require_once(dirname(dirname(__FILE__))."/sdk/AlibabaAliqinFcSmsNumSendRequest.php");
require_once(dirname(dirname(__FILE__))."/sdk/RequestCheckUtil.php");
require_once(dirname(dirname(__FILE__))."/sdk/ResultSet.php");
require_once(dirname(dirname(__FILE__))."/sdk/TopLogger.php");

/**
* 阿里大于插件控制器
* @Author: Kai <maifakai@126.com>
*/
class SmsMsg extends Common
{
    /**
    * 短信发送方法
    * @Author: Kai <maifakai@126.com>
    * @param string $mobile 接收人手机号
    * @param array $param 短信模版变量参数
    * @param string $template 短信模版Id
    * @return boolean
    */
    public function send($mobile, $param = [], $template = '')
    {
        $data = []; //请求参数
        //获取插件配置
        $plugin_config = plugin_config('alidayu');
        if ($plugin_config['sms_switch'] == '0'){
            $this->error('短信功能尚未开启');
        }
        $data['template'] = empty($template) ? $plugin_config['template'] : $template;
        $data['mobile'] = $mobile;
        $data['param'] = $param;
        $validate = new Validate([
            ['param','require|array','参数必填|参数必须为数组'],
            ['mobile','require|/1[34578]{1}\d{9}$/','手机号错误|手机号错误'],
            ['template','require','模板id错误'],
        ]);
        if (!$validate->check($data)) {
            return $validate->getError();
        }
        
        $sms_id = '';
        if ($plugin_config['sms_jilu'] == '1'){
            //创建短信发送记录
            $sms_item = [
                'uid' => '',
                'mobile' => $data['mobile'],
                'sign_name' => $plugin_config['FreeSignName'],
                'template_code' => $data['template'],
                'date_json' => json_encode($data),
                'create_time' => time(),
                'status' => 0
            ];
            $sms_id = AlidayuSms::create($sms_item)->getData('id');
        }
        
        //请求发送短信操作
        define('TOP_SDK_WORK_DIR', CACHE_PATH.'sms_tmp/');
        define('TOP_SDK_DEV_MODE', false);
        $c = new \TopClient();
        $c->appkey = $plugin_config['appkey'];                      //阿里大于APPKEY
        $c->secretKey = $plugin_config['appsecret'];                //阿里大于secretKey
        $req = new \AlibabaAliqinFcSmsNumSendRequest();
        $req->setExtend('');                                        //接口回传参数，接口将原样返回该字符串。
        $req->setSmsType('normal');                                 //短信类型，传入值请填写normal
        $req->setSmsFreeSignName($plugin_config['FreeSignName']);   //短信签名
        $req->setSmsParam(json_encode($data['param']));             //短信模版参数
        $req->setRecNum($data['mobile']);                           //接收人手机号
        $req->setSmsTemplateCode($plugin_config['template']);       //短信模版ID
        $result = $c->execute($req);
        $result = $this->_simplexml_to_array($result);
        if(isset($result['code'])){
            if ($plugin_config['sms_jilu'] == '1'){
                AlidayuSms::update(['status'=>2, 'update_time'=>time()], ['id'=>$sms_id]);
            }
            return $result['sub_code'];
        }
        if ($plugin_config['sms_jilu'] == '1'){
            AlidayuSms::update(['status'=>1, 'update_time'=>time()], ['id'=>$sms_id]);
        }
        return true;
    }

    /**
    * XML对象转换成数组方法
    * @Author: Kai <maifakai@126.com>
    * @param obj $obj XML对象
    * @return array
    */
    private function _simplexml_to_array($obj)
    {
        if(count($obj) >= 1){
            $result = $keys = [];
            foreach($obj as $key=>$value){
                isset($keys[$key]) ? ($keys[$key] += 1) : ($keys[$key] = 1);
                if( $keys[$key] == 1 ){
                    $result[$key] = $this->_simplexml_to_array($value);
                }elseif( $keys[$key] == 2 ){
                    $result[$key] = [$result[$key], $this->_simplexml_to_array($value)];
                }else if( $keys[$key] > 2 ){
                    $result[$key][] = $this->_simplexml_to_array($value);
                }
            }
            return $result;
        }else if(count($obj) == 0){
            return (string)$obj;
        }
    }

}